package com.example.netty.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author zclever <304078606@qq.com>
 * @date 2021-03-03
 */
@Component
@ChannelHandler.Sharable
public class PingHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(PingHandler.class);

    /**
     * 客户端在一定的时间没有动作就会触发这个事件
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event=(IdleStateEvent)evt;

            if (event.state()== IdleState.READER_IDLE){
                logger.info("读空闲");
            }else if(event.state()==IdleState.WRITER_IDLE){
                logger.info("写空闲");
            }else if(event.state()==IdleState.ALL_IDLE){
                logger.info("读写都空闲你，关闭通道");
                ctx.channel().close();
            }
        }
    }
}